<template>
	<div ref="chartRef" class="chart"></div>
</template>
<script lang="ts" setup>
import * as echarts from 'echarts';
import { useThemeConfig } from '/@/stores/themeConfig';
import { storeToRefs } from 'pinia';
import { computed, onMounted, onUnmounted, ref, shallowRef, watch } from 'vue';

const props = withDefaults(
	defineProps<{
		// data
		data:any[];
		// title
		title: string;
		// List location
		listPosition: string;
		// Outer diameter size
		outerDiameter: string;
		// Inner diameter size
		innerDiameter: string;
		// Show label or not
		isLabel: boolean;
		// Show label unit
		labelUnit: string;
	}>(),
	{
		title: '',
		listPosition: 'bottom',
		outerDiameter: '60%',
		innerDiameter: '40%',
		isLabel: true,
		labelUnit: ''
	}
);
const chartRef = ref<HTMLDivElement>();
const myChart = shallowRef();
const option = computed(() => ({
	title: {
		text: props.title
	},
	tooltip: {
		trigger: 'item',
		confine: true,
		extraCssText: 'white-space: normal; word-break: break-all;'
	},
	legend: {
		type: 'scroll',
		top: props.listPosition
	},
	series: [
		{
			type: 'pie',
			radius: [props.innerDiameter, props.outerDiameter],
			label: {
				show: props.isLabel,
				formatter: `{b}({c}${props.labelUnit})`
			},
			emphasis: {
				label: {
					show: true,
					fontSize: 20,
				}
			},
			tooltip: {
				formatter: (params:any) => {
					const data = params.data;
					let template = '';
					if (data.tooltipData && data.tooltipData.length) {
						template = `
							<div>
								<p>${data.name} ${data.value}${props.labelUnit}</p>
								<p>${data.name} ${data.tooltipData.join(',')}</p>
							</div>
						`;
					} else {
						template = `
							<div>
								<p>${data.name} ${data.value}${props.labelUnit}</p>
							</div>
						`;
					}
					return template;
				}
			},
			data: props.data[0] !== null ? props.data : []
		}
	]
}));
// Draw chart
const drawChart = () => {
	if (chartRef.value) {
		if (!myChart.value) {
			myChart.value = echarts.init(chartRef.value);
			myChart.value.showLoading({
				text: '图表加载中...',
				fontSize: '16px',
				maskColor: '#ffffff',
			});
		}
		myChart.value.setOption(option.value, true);
	}
};
// Reset Chart Container
const resize = () => {
	myChart.value.resize({
		animation: {
			duration: 200,
			easing: 'linear'
		}
	});
};
// Data change and redraw the chart
watch(
	() => props.data,
	() => {
		drawChart();
		myChart.value.hideLoading();
	}
);

const storesThemeConfig = useThemeConfig();
const { themeConfig } = storeToRefs(storesThemeConfig);
watch(
	() => themeConfig.value.isCollapse,
	() => {
		setTimeout(() => {
			resize();
		}, 500);
	}
);
onMounted(() => {
	drawChart();
	window.addEventListener('resize', resize);
});
onUnmounted(() => {
	window.removeEventListener('resize', resize);
});
</script>
<style lang="scss" scoped>
.chart{
    width: 100%;
    height: 100%;
}
</style>